<?php

namespace app\index\model;

use think\Model;
use think\Cache;

class Qrcode extends Model
{
    protected $pk = 'id';

    public function getOrderStatusAttr($v, $d){
        $isEx = SendOrder::where('send_qrcode_id', $d['id'])->where('send_status', '<>', 3)->find();
        return empty($isEx)? true:false;
    }

    public function getCodeAttr($v, $d){
        $codes = json_decode($d['kdcode']);
        $code = '';
        foreach ($codes as $v) {
            $content = Express::where('billcode', $v)->value('content');
            if(!empty($content)){
                $code .=  substr($content, 0, 8).'   ' ;
            }
        }
        return $code;
    }

    /**
     * 生成二维码
     */
    public function insertQr($orderNo){
        try {
            //生成二维码$qrcode
            $qr = \qrcode\BulidQrcode::bulidQr(json_encode($orderNo));
            if($qr && cache($orderNo)){
                $this->save([
                    'uid'   => session('user.id'),
                    'billcode' => $orderNo,
                    'qrcode' => $qr,
                    'kdcode' => cache($orderNo)
                ]);
                Express::where('billcode', 'in', json_decode(cache($orderNo)))->update(['status' => 1]);
                cache($orderNo, NULL);
                Member::where('memb_id', session('user.id'))->inc('memb_count', 1)->update();
                return mesg(0, 'success');
            }else{
                return mesg(-1, '二维码生成失败');
            }
        } catch (\Throwable $th) {
            throw $th;
            // return mesg(-5, $th->getMessage());
        }
    }
}
